package redis

import (
	"context"
	"strings"
	"time"

	"gitee.com/fanshuaiself/wss-gateway/constants"
	"gitee.com/fanshuaiself/wss-gateway/pkg/nacos"
	"github.com/go-redis/redis/v8"
	log "github.com/sirupsen/logrus"
	"github.com/spf13/viper"
)

var (
	ctx = context.Background()
	rClient *redis.Client
)

func Init(config *constants.Config) {
	appName := config.NacosServiceName

	properties, err := nacos.GetConfig(appName, appName)
	if err != nil {
		log.Fatal(err)
	}

	viper.SetConfigType("properties")
	if err = viper.ReadConfig(strings.NewReader(properties)); err != nil {
		log.Fatal(err)
	}

	hostname := viper.GetString("redis.hostname")
	password := viper.GetString("redis.password")
	db := viper.GetInt("redis.db")

	rClient = redis.NewClient(&redis.Options{
		Addr: hostname,
		Password: password,
		DB: db,
	})
}

func Get(key string) (string, error) {
	return rClient.Get(ctx, key).Result()
}

func Set(key, value string, expire time.Duration) error {
	return rClient.Set(ctx, key, value, expire).Err()
}

func Expire(key string, expire time.Duration) (bool, error) {
	return rClient.Expire(ctx, key, expire).Result()
}

func Del(key string) (int64, error) {
	return rClient.Del(ctx, key).Result()
}

const delScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"
func DelByValue(key, value string) error {
	return rClient.Eval(ctx, delScript, []string{key}, value).Err()
}
